<template>
  <el-tabs v-if="multiPage" v-model="active" @tabChange="tabChange"
      type="border-card" closable @tabRemove="tabRemove"
      class="portal-tags-wrapper">
    <el-tab-pane v-for="item in views" :name="item.path" :label="item.label"/>
  </el-tabs>
</template>
<script setup>

import {computed, nextTick, reactive, shallowRef, watch} from 'vue';
import {useRoute, useRouter} from 'vue-router';
import store from '@/store';
import {getComponentName} from '@/utils';
import {ElNotification} from 'element-plus';

defineOptions({name: 'PortalTags'});
const views = reactive([]);
const route = useRoute();
const router = useRouter();
const active = shallowRef();

const multiPage = computed(() => store.getters.multiPage)
const reloadFlag = store.getters.reloadFlag;
const cachedViews = store.getters.cachedViews;

function tabChange(path) {
  router.push(path)
}

function tabRemove(path) {
  let compName = store.state.routePathComponentMap[path];
  store.state.reloadFlag = false;
  let index = store.state.cachedViews.findIndex(item => item === compName);
  if (index >= 0) {
    store.state.cachedViews.splice(index, 1);
  }
  nextTick(() => {
    store.state.reloadFlag = true;
    removeAndChangeRoute(path);
  })
}

function removeAndChangeRoute(path) {
  let index = views.findIndex(item => item.path ===path);
  if (index >= 0) {
    if (views.length === 1 && views[0].path === '/dashboard') {

    } else {
      views.splice(index, 1);
    }
  }
  if (index < views.length) {
    router.push(views[index]);
  } else {
    index--;
    if (index >= 0) {
      router.push(views[index].path);
    } else {
      router.push('/')
    }
  }
}

watch(() => route.path, (newPath, oldPath) => {
  let view = views.find(v => v.path === newPath);
  active.value = newPath;
  if (!view)  {
    views.push({
      label: route.name,
      path: newPath
    })
  }
}, {
  immediate: true
})
</script>
<style lang="scss">
.portal-tags-wrapper {
  margin-top: -1px;
}
.portal-tags-wrapper,
.portal-tags-wrapper .el-tabs {
  border-bottom: none !important;
}
.portal-tags-wrapper .el-tabs__content {
  display: none;
}
</style>